package com.num2.controller.xjg;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.num2.util.RandomCode;

@Controller
@RequestMapping("/random/code") 
public class RandomCodeController { 
  @RequestMapping("/generate.do") 
  public void generateCode(HttpServletResponse response,HttpSession session) { 
    // 验证码图片宽度，单位像素 
    int width = 120; 
    // 验证码图片高度，单位像素 
    int height = 30; 
    // 验证码图片格式 
    String format = "png"; 
    // 验证码字符长度 
    int len = 4; 
  
    // 设置图片格式 
    response.setContentType("image/" + format); 
   
    // 禁止浏览器缓存图片 
    response.setHeader("Pragma", "no-cache"); 
    response.setHeader("Cache-Control", "no-cache"); 
    response.setDateHeader("Expires", 0); 
  
    String code = RandomCode.randomString(len); 
    //System.out.println(code);
    //将获取到的验证码放入session当中
    session.setAttribute("code", code);
    
    // 把图片输出到response输出流 
    try { 
      RandomCode.write(code, width, height, response.getOutputStream(), format); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
} 

